<script setup lang="ts">
import {computed, ref, watch} from 'vue';
import { type PropType } from 'vue';
import type { CheckboxValueType } from 'element-plus';

interface RuleItem {
  id: string | number;
  name: string;
  description: string;
}

const props = defineProps({
  modelValue: { type: Array, default: () => [] },
  rules: {
    type: Array as PropType<RuleItem[]>,
    required: true,
    default: () => [],
  },
  height: { type: String, default: '200px' },
});
const selected=ref<CheckboxValueType[]>()
const emit = defineEmits(['update:modelValue']);

// 监听rules变化，重置选中值
watch(
  () => props.rules,
  () => {
    emit('update:modelValue', []);
  },
  { deep: true }
);

// 计算全选状态
const checkAll = computed(() => {
  return props.rules.length > 0 && props.modelValue.length === props.rules.length;
});

// 计算部分选择状态
const isIndeterminate = computed(() => {
  return props.modelValue.length > 0 && props.modelValue.length < props.rules.length;
});

const handleCheckAllChange = (val: CheckboxValueType) => {
  selected.value = val ? props.rules.map(i=>i.id): [];
  emit('update:modelValue', props.rules);
};

const handleCheckedRulesChange = (value: CheckboxValueType[]) => {
  const rules = props.rules.filter((item) => value.includes(item.id));
  emit('update:modelValue', rules);
};
</script>

<template>
  <div
    style="width: 100%; overflow: auto"
    :style="{ height: props.height }"
    v-if="props.rules.length"
  >
    <el-checkbox
      :model-value="checkAll"
      :indeterminate="isIndeterminate"
      @change="handleCheckAllChange"
      class="checkbox"
    >
      全部规则({{ modelValue.length + '/' + props.rules.length }})
    </el-checkbox>
    <el-checkbox-group
      class="checkbox"
      v-model="selected"
      @change="handleCheckedRulesChange"
    >
      <el-checkbox
        style="display: block"
        v-for="item in props.rules"
        :key="item.id"
        :value="item.id"
      >
        {{ item.name }}
      </el-checkbox>
    </el-checkbox-group>
  </div>
  <el-empty
    v-else
    style="width: 100%"
    :image-size="100"
    description="暂无规则"
  />
</template>

<style scoped lang="scss">
.checkbox {
  width: 100%;
  padding: 10px;
  margin-bottom: 10px;
  background: #fff;
  border-radius: 4px;
}

:deep(.el-checkbox) {
  width: 100%;

  .el-checkbox__label {
    display: inline-block;
    width: calc(100% - 24px); // 24px是复选框的宽度
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
</style>
